<?php

/*
 * CakePHP Version 2.2.3
 */

App::uses('Controller', 'Controller');
App::uses('AuthComponent', 'Controller/Component');
App::uses('CakeEmail', 'Network/Email');

$www = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], "/", 1));

define('WWW', $www . '/');

require_once(APPLIBS . "funciones.php");
require_once(APPLIBS . "presentation.php");
require_once(APPLIBS . "menu.php");

class AppController extends Controller {

    public $render = null;
    public $search_list = null;
    public $maint = null;
    public $helpers = array('Html', 'Form', 'Session', 'Validation', 'Presentation');
    public $components = array(
        'Session',
        'Auth' => array(
            'loginAction' => array('plugin' => 'admin', 'controller' => 'users', 'action' => 'login'),
            'loginRedirect' => array('plugin' => null, 'controller' => 'pages', 'action' => 'display'), # homepage
            'logoutRedirect' => array('plugin' => 'admin', 'controller' => 'users', 'action' => 'login'),
            'authorize' => array('Controller'),
            'authError' => 'No estás autorizado a acceder a esta ubicación.'
        )
    );

    protected function getModelName() {
        return ucfirst($this->modelClass);
    }

    protected function getModel() {
        $modelo = $this->modelClass;
        return $this->$modelo;
    }

    private function getConfiguration() {
        $session_config = $this->Session->read("Configuration");
        if (isset($session_config) && is_array($session_config)) {
            return $session_config;
        }

        $model = $this->getModel();
        $sqlarray = $model->query("SELECT * FROM configurations LIMIT 1");

        $this->Session->write("Configuration", $sqlarray[0]['configurations']);
        return $sqlarray[0]['configurations'];
    }

    private function getPermisos() {
        $session_permisos = $this->Session->read("Permisos");
        if (isset($session_permisos) && is_array($session_permisos)) {
            return $session_permisos;
        }

        $session_auth = $this->Session->read('Auth');
        $rol = $session_auth['User']['Rol'];

        $model = $this->getModel();
        $sqlarray = $model->query("SELECT p.controller, p.action FROM permisos p
                                   JOIN permisos_rols pr ON pr.permiso_id=p.id
                                   WHERE pr.rol_id='" . $rol['id'] . "'");

        $permisos = array();
        foreach ($sqlarray as $permiso) {
            $permisos[$permiso['p']['controller']][] = $permiso['p']['action'];
        }

        $this->Session->write("Permisos", $permisos);
        return $sqlarray;
    }

    public function beforeFilter() {
        global $MODEL, $CONTROLLER, $MENU;
        $MODEL = $this->getModel();
        $CONTROLLER = $this;

        $user = $this->Auth->user();
        if (isset($user)) {
            $this->set('PERMISOS', $this->getPermisos());
        }

        $this->set('MODEL', $MODEL);
        $this->set('CONTROLLER', $this);
        $this->set('CONFIGURATION', $this->getConfiguration());
        $this->set('USER', $user);
        $this->set('MENU', $MENU);
    }

    public function isAuthorized() {
        $controller = strtolower($this->name);
        $action = strtolower($this->action);
        if ($action == "view") {
            $action = "index";
        }

        return $this->tienePermiso($controller, $action);
    }

    function generarMenu($lista) {
        $lista = $this->filtrarMenu($lista);

        $html = "";
        foreach ($lista as $key => $value) {
            $html.= '<li>';
            if (is_array($value)) {
                $html.= '<a href="#">' . $key . '</a>';
                $html.= '<ul>';
                $html.= $this->generarMenu($value);
                $html.= '</ul>';
            } else {
                if (strpos($value, "|") !== false) {
                    $array = explode("|", $value);
                    $html.= '<a href="' . WWW . (isset($array[2]) ? $array[2] . '/' : '') . $array[0] . '/' . $array[1] . '">' . $key . '</a>';
                } else {
                    $html.= '<a href="' . $value . '">' . $key . '</a>';
                }
            }
            $html.= '</li>';
        }
        return $html;
    }

    public function filtrarMenu($lista) {
        $array = array();
        foreach ($lista as $key => $value) {
            if (is_array($value)) {
                $array[$key] = $this->filtrarMenu($value);
                if (empty($array[$key])) {
                    unset($array[$key]);
                }
            } else {
                if (strpos($value, "|") !== false) {
                    list($controller, $action) = explode("|", $value);
                    if ($this->tienePermiso($controller, $action)) {
                        $array[$key] = $value;
                    }
                } else {
                    $array[$key] = $value;
                }
            }
        }
        return $array;
    }

    // Acciones que pueden realizar los usuarios logueados
    public function tienePermiso($controller, $action) {
        $controller = strtolower($controller);
        $action = strtolower($action);

        // ajaxID (para tablas asociadas muchos a muchos)
        if ($action == "ajaxid" || $action == "ajax") {
            return true;
        }

        // Datos Personales
        if ($controller == "datos" && $action == "edit") {
            return true;
        }

        // Presentations
        if ($controller == "remotes" && $action == "request") {
            return true;
        }

        $permisos = $this->getPermisos();
        $array = explode("/", $action);
        $action = $array[0];
        if (isset($permisos[$controller]) && (in_array("*", $permisos[$controller]) || in_array($action, $permisos[$controller]))) {
            return true;
        }
        return false;
    }

    protected function filtrosActivos() {
        $array = array();
        if (!empty($this->request->data)) {
            foreach ($this->search_list['filters'] as $filtro) {
                $array_field = explode(".", $filtro['name']);
                if (count($array_field) > 1) {
                    $model = $array_field[0];
                    $field = $array_field[1];
                } else {
                    $model = $this->getModelName();
                    $field = $filtro['name'];
                }
                if (isset($this->request->data[$model])) {
                    $val = $this->request->data[$model][$field];
                    if (!empty($val)) {
                        $array[] = array("data" => $filtro, "value" => $val);
                    }
                }
            }
        }
        return $array;
    }

    protected function drawFiles($id = 0) {
        if (empty($this->maint['files'])) {
            return array();
        }

        $model = $this->getModelName();
        $files = $this->maint['files'];
        $files['files'] = $this->$model->Query("SELECT * FROM files WHERE model='" . $model . "' AND model_id=" . $id);
        foreach (array_keys($files['files']) as $key) {
            $files['files'][$key] = $files['files'][$key]['files'];
        }
        $files['actions'] = isset($files['actions']) ? $files['actions'] : array("A", "D");
        $files['parentActions'] = isset($files['parentActions']) ? $files['parentActions'] : array("A", "E", "V");
        return $files;
    }

    protected function drawTables($id = 0) {
        $model = $this->getModelName();
        $array_tables = array();
        if (isset($this->maint['tables']) && is_array($this->maint['tables'])) {
            foreach ($this->maint['tables'] as $description => $table) {
                $obj = $this->$model->$table['model'];
                if (empty($obj)) {
                    throw new NotFoundException(__('No existe el modelo ' . $table['model'] . ' indicado para la tabla asociada de ' . $description . ' o no esta asociado al modelo ' . $model . '.'));
                }

                if (isset($obj->hasAndBelongsToMany[$model])) {
                    $assoc = true;
                } elseif (isset($obj->belongsTo[$model])) {
                    $assoc = false;
                } else {
                    throw new NotFoundException(__('No existe la relación muchos a muchos o uno a muchos entre el modelo ' . $model . ' y ' . $table['model'] . '.'));
                }

                if ($assoc) {
                    $pk = $obj->primaryKey;
                    $fk = $obj->hasAndBelongsToMany[$model]['foreignKey'];
                    $assoc_fk = $obj->hasAndBelongsToMany[$model]['associationForeignKey'];
                    $join_table = $obj->hasAndBelongsToMany[$model]['joinTable'];
                    $query_assoc = "(SELECT " . $pk . " FROM " . $join_table . " WHERE " . $fk . "=" . $table['model'] . "." . $pk . " AND " . $assoc_fk . "=" . $id . ") !=";
                    $options['conditions'] = array($query_assoc => null);
                } else {
                    $fk = $obj->belongsTo[$model]['foreignKey'];
                    $options['conditions'] = array($table['model'] . "." . $fk => $id);
                }

                // Seteo el required en los campos de la tabla asociada
                foreach ($table['fields'] as $key => $value) {
                    $validate = $obj->validate;
                    $table['fields'][$key]["required"] = isset($validate[$value["name"]]['required']);
                }

                $options['fields'] = array($table['model'] . '.*');
                $options['order'] = $table['order'];
                $array_tables[$description]['list'] = $this->$model->$table['model']->find('all', $options);
                $array_tables[$description]['fields'] = $table['fields'];
                $array_tables[$description]['model'] = $table['model'];
                $array_tables[$description]['assoc'] = ($assoc ? 1 : 0);
                $array_tables[$description]['plugin'] = $obj->plugin;
                $array_tables[$description]['actions'] = isset($table['actions']) ? $table['actions'] : array("A", "E", "D");
                $array_tables[$description]['parentActions'] = isset($table['parentActions']) ? $table['parentActions'] : array("A", "E", "V");
            }
        }
        return $array_tables;
    }

    private function deleteFile($id, $filename) {
        $model = $this->getModelName();
        $root = WWW_ROOT . 'files/';

        $subpath = "";
        for ($j = 0; $j < 5; $j++) {
            $subpath.= substr($filename, ($j * 2), 2) . "/";
        }

        if (unlink($root . $subpath . $filename)) {
            $this->$model->Query("DELETE FROM files WHERE id='" . $id . "'");
        }
    }

    private function processFiles($id) {
        $model = $this->getModelName();
        $tmp_root = ROOT . '/' . APP_DIR . '/tmp/files/';
        $root = WWW_ROOT . 'files/';

        if (isset($this->request->data['table']['files'])) {
            foreach ($this->request->data['table']['files'] as $file) {
                if (is_array($file)) {
                    // Agregar Archivo
                    if ($file['do'] == 'A') {
                        //Agrego 5 subniveles por el archivo
                        $subpath = "";
                        for ($j = 0; $j < 5; $j++) {
                            $subpath.= substr($file['file'], ($j * 2), 2) . "/";
                            if (!is_dir($root . $subpath)) {
                                mkdir($root . $subpath);
                            }
                        }

                        $tmp = $tmp_root . $file['file'];
                        $target = $root . $subpath . $file['file'];
                        copy($tmp, $target);
                        unlink($tmp);

                        $this->$model->Query("INSERT INTO files (fecha_carga, model, model_id, filename, name, type, size)
                                          VALUES (NOW(), '" . $model . "', " . $id . ", '" . $file['file'] . "', '" . $file['name'] . "', '" . $file['type'] . "', " . $file['size'] . ")");
                    }

                    // Borrar Archivo
                    if ($file['do'] == 'D') {
                        $this->deleteFile($file['id'], $file['file']);
                    }
                }
            }
        }
    }

    private function processTable($description, $table, $id) {
        $model = $this->getModelName();

        $obj = $this->$model->$table['model'];
        if (empty($obj)) {
            throw new NotFoundException(__('No existe el modelo ' . $table['model'] . ' indicado para la tabla asociada de ' . $description . ' o no esta asociado al modelo ' . $model . '.'));
        }

        if (isset($obj->hasAndBelongsToMany[$model])) {
            $assoc = true;
        } elseif (isset($obj->belongsTo[$model])) {
            $assoc = false;
        } else {
            throw new NotFoundException(__('No existe la relación muchos a muchos o uno a muchos entre el modelo ' . $model . ' y ' . $table['model'] . '.'));
        }

        unset($this->request->data['table'][$table['model']]['assoc']);

        if ($assoc) {
            if (empty($obj->hasAndBelongsToMany[$model])) {
                throw new NotFoundException(__('No existe la relación muchos a muchos entre ' . $model . ' y ' . $table['model'] . '.'));
            }

            $fk = $obj->hasAndBelongsToMany[$model]['foreignKey'];
            $assoc_fk = $obj->hasAndBelongsToMany[$model]['associationForeignKey'];
            $join_table = $obj->hasAndBelongsToMany[$model]['joinTable'];

            foreach ($this->request->data['table'][$table['model']] as $row) {
                if (!isset($row['pk'])) {
                    throw new NotFoundException(__('La tabla asociada para ' . $description . ' no tiene seteado el campo PK.'));
                }

                if ($row['do'] == "A") {
                    $this->$model->Query("INSERT INTO " . $join_table . " (" . $fk . ", " . $assoc_fk . ") VALUES ('" . $row['pk'] . "', '" . $id . "')");
                } elseif ($row['do'] == "D") {
                    $this->$model->Query("DELETE FROM " . $join_table . " WHERE " . $fk . "='" . $row['pk'] . "' AND " . $assoc_fk . "='" . $id . "'");
                } elseif ($row['do'] == "E") {
                    $this->$model->Query("DELETE FROM " . $join_table . " WHERE " . $fk . "='" . $row['old_pk'] . "' AND " . $assoc_fk . "='" . $id . "'");
                    $this->$model->Query("INSERT INTO " . $join_table . " (" . $fk . ", " . $assoc_fk . ") VALUES ('" . $row['pk'] . "', '" . $id . "')");
                }
            }
        } else {
            if (empty($obj->belongsTo[$model])) {
                throw new NotFoundException(__('No existe la relación uno a muchos entre el modelo ' . $model . ' y ' . $table['model'] . '.'));
            }

            $fk = $obj->belongsTo[$model]['foreignKey'];
            if (isset($this->request->data['table'][$table['model']])) {
                foreach ($this->request->data['table'][$table['model']] as $row) {
                    $row[$fk] = $id;
                    $do = $row['do'];
                    unset($row['do']);
                    if (isset($row['pk'])) {
                        $pk = $row['pk'];
                        unset($row['pk']);
                    }
                    if ($do == "A") {
                        $obj->saveAll($row);
                    } elseif ($do == "D") {
                        $obj->delete($pk, false);
                    } elseif ($do == "E") {
                        $obj->updateAll(array_map("addQuotes", $row), array($table['model'] . "." . $obj->primaryKey => $pk));
                    }
                }
            }
        }
    }

    protected function processData($array_data, $type) {
        $array = array();
        if (isset($array_data) && is_array($array_data) && !empty($type)) {
            foreach ($array_data as $modelName => $model) {
                if ($type == "fields") {
                    $array[$modelName] = array();
                }
                if (is_array($model) && !empty($model)) {
                    foreach ($model as $clave => $valor) {
                        if (!empty($valor) && substr($clave, 0, 1) != "_") {
                            if ($field_data = $this->getFieldData($modelName . "." . $clave, $type)) {
                                if ($type == "fields") {
                                    $value = $this->getFieldPresentationObj($field_data, $valor)->saveDbQuery();
                                    if (!empty($value)) {
                                        $array[$modelName][$clave] = $value;
                                    }
                                } else {
                                    foreach ($this->getFieldPresentationObj($field_data, $valor)->objectDBQuery() as $key => $value) {
                                        $array[$key] = $value;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $array;
    }

    protected function modelRowData($data) {
        $array = array();
        foreach ($data as $modelName => $model) {
            $array[$modelName] = array();
            foreach ($model as $field => $value) {
                if ($field_data = $this->getFieldData($modelName . "." . $field, "fields")) {
                    $loadDbQuery = $this->getFieldPresentationObj($field_data, $value)->loadDbQuery();
                    $array[$modelName][$field] = $loadDbQuery;
                } else {
                    $array[$modelName][$field] = $value;
                }
            }
        }
        return $array;
    }

    public function getFieldData($field_name, $type) {
        if ($type == "filters" || $type == "columns") {
            foreach ($this->search_list[$type] as $key => $value) {
                $name = $this->search_list[$type][$key]['name'];
                if ($name == $field_name) {
                    return $this->search_list[$type][$key];
                }
            }
        } else {
            foreach ($this->maint[$type] as $fieldset) {
                foreach ($fieldset as $key => $value) {
                    if (($this->getModelName() . "." . $fieldset[$key]['name']) == $field_name) {
                        return $fieldset[$key];
                    }
                }
            }
        }
        return false;
    }

    public function getFieldPresentationObj($field, $field_value) {
        $field['value'] = $field_value;
        if (isset($field['presentation'])) {
            if ($url = existePresentation($field['presentation'])) {
                include_once($url);
                if (strpos($field['presentation'], "::") !== false) {
                    list($path, $presentation) = explode("::", $field['presentation']);
                    $class = "PST_" . $presentation;
                } else {
                    $class = "PST_" . $field['presentation'];
                }
                if (class_exists($class)) {
                    return new $class($field);
                } else {
                    include_once(ROOT . '/app/Presentation/default/text.php');
                    return new PST_TEXT($field);
                }
            }
        }
        include_once(ROOT . '/app/Presentation/default/text.php');
        return new PST_TEXT($field);
    }

    protected function exportar($rows, $columns, $output = "excel") {
        require_once '../Lib/PHPExcel.php';

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Framework");
        $objPHPExcel->setActiveSheetIndex(0);

        $j = 65;
        foreach ($columns as $column) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($j) . "1", $column["label"]);
            $j++;
        }

        $i = 2;
        foreach ($rows as $row) {
            $j = 65;
            foreach ($columns as $column) {
                $array = explode(".", $column["name"]);
                if (count($array) == 2) {
                    $model = ucfirst($array[0]);
                    $field = $array[1];
                } else {
                    $model = $this->getModelName();
                    $field = $array[0];
                }

                $objPHPExcel->setActiveSheetIndex(0)->setCellValue(chr($j) . $i, $row[$model][$field]);
                $j++;
            }
            $i++;
        }
        $objPHPExcel->getActiveSheet()->setTitle('export');


        $filename = $this->name . "-" . date("YmdHis");

        if ($output == "excel") {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
            header('Cache-Control: max-age=0');

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
        } elseif ($output == "pdf") {
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment;filename="' . $filename . '.pdf"');
            header('Cache-Control: max-age=0');

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
            $objWriter->save('php://output');
        }
    }

    /* Métodos accesible vía WEB */

    public function index() {
        // Agrego el initial value al POST de los campos donde se seteo
        foreach ($this->search_list['filters'] as $filter) {
            if (!empty($filter['initialvalue'])) {
                $field = explode(".", $filter['name']);
                $this->request->data[$field[0]][$field[1]] = $filter['initialvalue'];
            }
        }

        // Si no vienen condiciones seteadas por default seteo un array vacio
        if (empty($this->search_list['conditions'])) {
            $this->search_list['conditions'] = array();
        }

        // Pagino usando las condiciones seteadas por default
        $this->paginate = array(
            'conditions' => $this->search_list['conditions']
        );

        if ($this->request->is('post') || !empty($this->request->data)) {
            $this->request->data['Cake'] = array(
                '_filter' => '1',
                '_output' => 'html'
            );

            // Pagino usando las condiciones seteadas por default mas los filtros utilizados
            $this->paginate = array(
                'conditions' => array_merge($this->paginate['conditions'], $this->processData($this->request->data, "filters"))
            );

            $rows = $this->paginate();

            if (isset($this->request->data['Cake']['_output'])) {
                $output = $this->request->data['Cake']['_output'];
                if ($output != "html") {
                    $this->exportar($rows, $this->columns, $output);
                    exit(0);
                }
            }
        } else {
            $rows = $this->paginate();
        }

        $this->set('outputs', array(
            "html" => "Web",
            "excel" => "Excel",
            "pdf" => "PDF"
        ));
        $this->set('filtros', $this->search_list['filters']);
        $this->set('filtros_activos', $this->filtrosActivos());
        $this->set('cols', $this->search_list['columns']);
        $this->set('rows', $rows);
        $this->set('actions', $this->search_list['actions']);

        if (isset($this->render) && is_array($this->render) && count($this->render) == 2) {
            return $this->render($this->render[0], $this->render[1]);
        }
        return $this->render('/index', $this->layout);
    }

    public function view($id = null) {
        $model = $this->getModelName();
        $this->set('fields', $this->maint['fields']);

        $this->$model->id = $id;
        if (!$this->$model->exists()) {
            throw new NotFoundException(__('Registro inexistente'));
        }

        $this->set('files', $this->drawFiles($id));
        $this->set('tables', $this->drawTables($id));
        $this->set('row', $this->modelRowData($this->$model->read(null, $id)));
        $this->set('return', isset($this->maint['return']) ? $this->maint['return'] : "index");
        $this->set('jsincludes', isset($this->maint['jsincludes']) ? $this->maint['jsincludes'] : array());

        if (isset($this->render) && is_array($this->render) && count($this->render) == 2) {
            return $this->render($this->render[0], $this->render[1]);
        }
        return $this->render('/view', $this->layout);
    }

    public function add() {
        $model = $this->getModelName();

        if ($this->request->is('post') || $this->request->is('put')) {
            // Obtiene los valores de los campos de acuerdo a sus presentation
            $request_data = $this->processData($this->request->data, "fields");

            // Trata de guardarlo
            $this->$model->create();
            if (!$data = $this->$model->save($request_data)) {
                $this->Session->setFlash(__('El registro no pudo ser ingresado'));
            }

            // Toma el ID generado
            $id = $data[$model]['id'];

            // Recorre la tabla de archivos
            if (isset($this->maint['files'])) {
                $this->processFiles($id);
            }

            // Recorre las tablas asociadas
            if (isset($this->maint['tables'])) {
                foreach ($this->maint['tables'] as $description => $table) {
                    $this->processTable($description, $table, $id);
                }
            }

            // Retorna al index
            $this->Session->setFlash(__('El registro ha sido ingresado correctamente'));
            $this->redirect(array('action' => isset($this->maint['return']) ? $this->maint['return'] : "index"));
        }

        $this->set('fields', $this->maint['fields']);
        $this->set('tables', $this->drawTables());
        $this->set('files', isset($this->maint['files']) ? $this->maint['files'] : false);
        $this->set('return', isset($this->maint['return']) ? $this->maint['return'] : "index");
        $this->set('jsincludes', isset($this->maint['jsincludes']) ? $this->maint['jsincludes'] : array());

        if (isset($this->render) && is_array($this->render) && count($this->render) == 2) {
            return $this->render($this->render[0], $this->render[1]);
        }
        return $this->render('/add', $this->layout);
    }

    public function edit($id = null) {
        $model = $this->getModelName();
        $this->$model->id = $id;

        if (!$this->$model->exists()) {
            throw new NotFoundException(__('Registro inexistente'));
        }
        if (($this->request->is('post') || $this->request->is('put')) && isset($this->request->data[$model]) && !isset($this->request->data['Cake']['_filter'])) {
            // Agrega datos al POST antes de guardar
            $this->request->data[$model]['fecha_modificacion'] = date("Y-m-d H:i:s");

            // Obtiene los valores de los campos de acuerdo a sus presentation
            $request_data = $this->processData($this->request->data, "fields");

            // Trata de guardarlo
            if (!$data = $this->$model->save($request_data)) {
                $this->Session->setFlash(__('El registro no pudo ser editado'));
            }

            // Recorre la tabla de archivos
            if (isset($this->maint['files'])) {
                $this->processFiles($id);
            }

            // Recorre las tablas asociadas
            if (isset($this->maint['tables'])) {
                foreach ($this->maint['tables'] as $description => $table) {
                    $this->processTable($description, $table, $id);
                }
            }

            // Retorna al index
            $this->Session->setFlash(__('El registro ha sido editado correctamente'));
            $this->redirect(array('action' => isset($this->maint['return']) ? $this->maint['return'] : "index"));
        }

        $this->set('files', $this->drawFiles($id));
        $this->set('fields', $this->maint['fields']);
        $this->set('row', $this->modelRowData($this->$model->read(null, $id)));
        $this->set('tables', $this->drawTables($id));
        $this->set('return', isset($this->maint['return']) ? $this->maint['return'] : "index");
        $this->set('jsincludes', isset($this->maint['jsincludes']) ? $this->maint['jsincludes'] : array());

        $data = $this->$model->read(null, $id);
        foreach ($data as $model_k => $model) {
            foreach ($model as $key => $value) {
                if ((strstr($key, "fecha") || strstr($key, "date")) && $key != 'fecha_carga' && $key != 'fecha_modificacion') {
                    $data[$model_k][$key] = fecha($value);
                }
            }
        }
        $this->request->data = $data;

        if (isset($this->render) && is_array($this->render) && count($this->render) == 2) {
            return $this->render($this->render[0], $this->render[1]);
        }
        return $this->render('/edit', $this->layout);
    }

    public function delete($id = null) {
        $model = $this->getModelName();

        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->$model->id = $id;
        if (!$this->$model->exists()) {
            throw new NotFoundException(__('Registro inexistente'));
        }
        if ($this->$model->delete()) {
            // Elimino los archivos asociados al registro del modelo
            $files = $this->$model->Query("SELECT id, filename FROM files WHERE model='" . $model . "' AND model_id=" . $id);
            foreach ($files as $file) {
                $this->deleteFile($file['files']['id'], $file['files']['filename']);
            }
            $this->$model->Query("DELETE FROM files WHERE model='" . $model . "' AND model_id=" . $id);

            $this->Session->setFlash(__('El registro ha sido eliminado correctamente'));
            $this->redirect(array('action' => isset($this->maint['return']) ? $this->maint['return'] : "index"));
        }

        $this->Session->setFlash(__('El registro no pudo ser eliminado'));
        $this->redirect(array('action' => isset($this->maint['return']) ? $this->maint['return'] : "index"));
    }

    public function ajaxID($id = null) {
        $model = $this->getModelName();

        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }

        $this->$model->id = $id;
        if (!$this->$model->exists()) {
            throw new NotFoundException(__('Registro inexistente'));
        }

        $this->set('data', json_encode($this->$model->findById($id)));
        return $this->render('/ajax', 'ajax');
    }

    public function ajax($presentation, $function, $params = '') {
        if (!$this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        if (empty($presentation)) {
            $this->set('data', json_encode(array("status" => "error", "desc" => "Presentation missing")));
            return $this->render('/ajax', 'ajax');
        }
        if (empty($function)) {
            $this->set('data', json_encode(array("status" => "error", "desc" => "Function missing")));
            return $this->render('/ajax', 'ajax');
        }

        if ($url = existePresentation($presentation)) {
            include_once($url);
            $class = "PST_" . $presentation;
            if (class_exists($class)) {

                $obj = new $class(array());
                if (method_exists($obj, $function)) {
                    $data = $obj->$function($params);
                } else {
                    $this->set('data', json_encode(array("status" => "error", "desc" => "Unknown function")));
                    return $this->render('/ajax', 'ajax');
                }
            }
        } else {
            $this->set('data', json_encode(array("status" => "error", "desc" => "Unknown presentation")));
            return $this->render('/ajax', 'ajax');
        }

        if (empty($data)) {
            $this->set('data', json_encode(array("status" => "error", "desc" => "Data missing")));
            return $this->render('/ajax', 'ajax');
        }

        if (is_array($data)) {
            $this->set('data', json_encode($data));
        } else {
            $this->set('data', $data);
        }

        return $this->render('/ajax', 'ajax');
    }

}
